package com.wanglibao.woodtrade.woodtrade.ui.fragment;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.ShopOrder;
import com.wanglibao.woodtrade.woodtrade.model.WoodType;
import com.wanglibao.woodtrade.woodtrade.model.impl.ShopOrderImpl;
import com.wanglibao.woodtrade.woodtrade.model.impl.WoodTypeImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.BuyActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.CommodityActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.CommodityAndSupplyActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.InformationDetailActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.SearchActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.ShopActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.SupplyAndDemendActivity;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.HomeFragmentHotInformationListViewAdapter;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.HomeFragmentHotShopListViewAdapter;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.HomeFragmentRecommendAdapter;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.ItemLvFragmentHomeDeandAdapter;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.model.Commodity;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.model.InformationItem;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.model.NewDemand;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.model.ShopItem;
import com.wanglibao.woodtrade.woodtrade.util.CommonUtil;
import com.wanglibao.woodtrade.woodtrade.util.DateUtils;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshScrollView;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshScrollViewBase;
import com.wanglibao.woodtrade.woodtrade.widget.SVListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 首页
 * Created by lugg on 2016/5/10.
 */
public class HomeFragment extends BaseFragment implements View.OnFocusChangeListener {


    @Bind(R.id.sv_fragment_home)
    public PullToRefreshScrollView sv_fragment_home;

    @Bind(R.id.edit_fragment_home_search)
    EditText edit_fragment_home_search;

    @Bind(R.id.tv_fragment_home_supplyanddemand)
    TextView tv_fragment_home_supplyanddemand;

    @Bind(R.id.list_fragment_home_commodity)
    SVListView list_fragment_home_commodity;

    @Bind(R.id.svlist_fragment_home_shop)
    SVListView svlist_fragment_home_shop;

    @Bind(R.id.svlist_fragment_home_information)
    SVListView svlist_fragment_home_information;

    @Bind(R.id.list_fragment_home_demand)
    SVListView list_fragment_home_demand;

    @Bind(R.id.rl_fragment_home_title)
    RelativeLayout rl_fragment_home_title;
    @Bind(R.id.edit_fragment_home_search_top)
    EditText edit_fragment_home_search_top;

    @Bind(R.id.rl_fragment_home_message)
    RelativeLayout rl_fragment_home_message;
    @Bind(R.id.tv_fragment_home_message)
    TextView tv_fragment_home_message;
    @Bind(R.id.tv_fragment_home_message_date)
    TextView tv_fragment_home_message_date;

    @Bind(R.id.tv_fragment_home_yesterday_trade)
    TextView tv_fragment_home_yesterday_trade;
    @Bind(R.id.tv_fragment_home_total_trade)
    TextView tv_fragment_home_total_trade;

    @Bind(R.id.ll_fragment_home_woodType)
    LinearLayout ll_fragment_home_woodType;

    @Bind(R.id.rl_fragment_home_shipping_order)
    RelativeLayout rl_fragment_home_shipping_order;
    @Bind(R.id.rl_fragment_home_order)
    RelativeLayout rl_fragment_home_order;

    int lastScrollY = 0;
    int edit_state = 1;

    int runnableOrderIndex = 0;
    List<ShopOrder> shopOrders = new ArrayList<>();
    int loadSize = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    public void refresh(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                sv_fragment_home.setRefreshing();
            }
        }, 300);
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void initView() {
        addViewClicklistener(tv_fragment_home_supplyanddemand);

        sv_fragment_home.setOnRefreshListener(new PullToRefreshScrollViewBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshScrollViewBase<ScrollView> refreshView) {
                getData();
                loadSize = 0;
            }
        });

        edit_fragment_home_search.setOnFocusChangeListener(this);
        edit_fragment_home_search_top.setOnFocusChangeListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            sv_fragment_home.getRefreshableView().setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    int top = edit_fragment_home_search.getTop();
                    top = top - CommonUtil.dip2px(HomeFragment.this.getContext(), 25);
                    lastScrollY = scrollY;
                    if (scrollY > top && edit_state == 1) {
                        edit_state = 2;
                        rl_fragment_home_title.setVisibility(View.VISIBLE);
                        edit_fragment_home_search.setVisibility(View.GONE);
                    } else if (top > scrollY && edit_state == 2) {
                        edit_state = 1;
                        rl_fragment_home_title.setVisibility(View.GONE);
                        edit_fragment_home_search.setVisibility(View.VISIBLE);
                    }
                }
            });
        }
        scrollViewTop();
        refresh();
    }

    private void initWoodType() {
        List<WoodType> woodTypeList = new WoodTypeImpl(getContext()).getAll();
        Drawable[] backgrounds = new Drawable[]{getResources().getDrawable(R.drawable.bg_fragment_home_type_item_1),
                getResources().getDrawable(R.drawable.bg_fragment_home_type_item_2),
                getResources().getDrawable(R.drawable.bg_fragment_home_type_item_3),
                getResources().getDrawable(R.drawable.bg_fragment_home_type_item_4)};

        LinearLayout linearlayout = null;
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(CommonUtil.dip2px(getContext(), 100), CommonUtil.dip2px(getContext(), 50));
        layoutParams.setMargins(0, 0, CommonUtil.dip2px(getContext(), 5), 0);
        ll_fragment_home_woodType.removeAllViews();
        for (int i = 0; i < woodTypeList.size(); i++) {
            linearlayout = (LinearLayout) View.inflate(getContext(), R.layout.linearlayout_woodtype, null);
            linearlayout.setBackgroundDrawable(backgrounds[i % 4]);
            linearlayout.setLayoutParams(layoutParams);
            TextView name = (TextView) linearlayout.findViewById(R.id.tv_linearlayout_woodtype_name);
            TextView sum = (TextView) linearlayout.findViewById(R.id.tv_linearlayout_woodtype_sum);
            name.setText(woodTypeList.get(i).name);
            sum.setText(woodTypeList.get(i).sum + "件");
            linearlayout.setTag(woodTypeList.get(i).id);
            linearlayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), CommodityAndSupplyActivity.class);
                    intent.putExtra("woodTypeId", v.getTag().toString());
                    startActivity(intent);
                }
            });
            ll_fragment_home_woodType.addView(linearlayout);
        }
    }


    public void getData() {

        //获取木材类型
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this,
                NetConfig.SERVER + NetConfig.TYPE_GOODS, NetConfig.categoryIndex, handler,
                "jsonObject", NetConfig.TaskId.categoryIndex, new Object[]{});
        jsonRPCAsyncTask.execute(new Void[]{});

        //获取 交易数据  SERVER_wangliwei
        jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER + NetConfig.TYPE_ORDER, NetConfig.get_trade, handler,
                "jsonObject", NetConfig.TaskId.get_trade, new Object[]{});
        jsonRPCAsyncTask.execute(new Void[]{});

        //获取所有交易动态信息
        jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER + NetConfig.TYPE_ORDER, NetConfig.shipping_order, handler,
                "jsonArray", NetConfig.TaskId.shipping_order, new Object[]{});
        jsonRPCAsyncTask.execute(new Void[]{});

        //获取最新求购信息
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("type", "0");
            jsonObject.put("page", "1");
            jsonObject.put("num", "3");
            jsonObject.put("category_one", "");
            jsonObject.put("category", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER + "?c=message", NetConfig.messageSendList, handler,
                "jsonObject", NetConfig.TaskId.messageSendList, new Object[]{jsonObject});
        jsonRPCAsyncTask.execute(new Void[]{});

        //获取 商品推荐  SERVER_wangxiaoming
        jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER + NetConfig.TYPE_GOODS, NetConfig.recommendGoodsLists, handler,
                "jsonObject", NetConfig.TaskId.recommendGoodsLists, new Object[]{1});
        jsonRPCAsyncTask.execute(new Void[]{});

        //获取热门商铺
        jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER + NetConfig.TYPE_STORE, NetConfig.storeRecommendList, handler,
                "jsonObject", NetConfig.TaskId.storeRecommendList, new Object[]{2});
        jsonRPCAsyncTask.execute(new Void[]{});

        //获取热门资讯
        jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER + NetConfig.TYPE_NEW, NetConfig.recommendNewList, handler,
                "jsonObject", NetConfig.TaskId.recommendNewList, new Object[]{4});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            loadSize++;
            Gson gson = new Gson();
            if (sv_fragment_home != null && sv_fragment_home.isRefreshing() && loadSize == 7) {
                sv_fragment_home.onRefreshComplete();
            }
            if (msg.arg2 != 2) {
                if (msg.arg1 == NetConfig.TaskId.get_trade) {//交易数据
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        tv_fragment_home_yesterday_trade.setText("¥" + jsonObject.getString("yesterday_trade")+"万元");
                        tv_fragment_home_total_trade.setText("¥" + jsonObject.getString("total_trade")+"万元");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (msg.arg1 == NetConfig.TaskId.shipping_order) { //滚动消息
                    shopOrders = gson.fromJson(msg.obj.toString(), new TypeToken<List<ShopOrder>>() {
                    }.getType());
                    if (shopOrders != null && shopOrders.size() > 0){
                        ShopOrderImpl shopOrder = new ShopOrderImpl(getContext());
                        shopOrder.deleteAll();
                        shopOrder.insertWithTransaction(shopOrders);
                        runnableOrderInfo();
                    }else{
                        rl_fragment_home_message.setVisibility(View.GONE);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rl_fragment_home_shipping_order.getLayoutParams();
                        layoutParams.setMargins(0,0,0,0);
                        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) rl_fragment_home_order.getLayoutParams();
                        layoutParams1.height = CommonUtil.dip2px(getContext(),67);

                    }
                } else if (msg.arg1 == NetConfig.TaskId.messageSendList) { //最新求购信息
                    final NewDemand newDemand = gson.fromJson(msg.obj.toString(), NewDemand.class);
                    ItemLvFragmentHomeDeandAdapter itemLvFragmentHomeDeandAdapter = new ItemLvFragmentHomeDeandAdapter(getContext(), newDemand);
                    list_fragment_home_demand.setAdapter(itemLvFragmentHomeDeandAdapter);
                    list_fragment_home_demand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(getActivity(), BuyActivity.class);
                            intent.putExtra("ID", newDemand.getList().get(position).getId());
                            intent.putExtra("type","1");
                            startActivity(intent);
                        }
                    });
                } else if (msg.arg1 == NetConfig.TaskId.recommendGoodsLists) {
                    final Commodity commodity = gson.fromJson(msg.obj.toString(), Commodity.class);
                    HomeFragmentRecommendAdapter homeFragmentRecommendAdapter = new HomeFragmentRecommendAdapter(getContext(), commodity);
                    list_fragment_home_commodity.setAdapter(homeFragmentRecommendAdapter);
                    list_fragment_home_commodity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(getActivity(), CommodityActivity.class);
                            intent.putExtra("id", commodity.getList().get(position).getGoods_id());
                            startActivity(intent);
                        }
                    });
                } else if (msg.arg1 == NetConfig.TaskId.storeRecommendList) {
                    final ShopItem shopItem = gson.fromJson(msg.obj.toString(), ShopItem.class);
                    HomeFragmentHotShopListViewAdapter homeFragmentHotShopListViewAdapter = new HomeFragmentHotShopListViewAdapter(getContext(), shopItem);
                    svlist_fragment_home_shop.setAdapter(homeFragmentHotShopListViewAdapter);
                    svlist_fragment_home_shop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(getActivity(), ShopActivity.class);
                            intent.putExtra("id", shopItem.getList().get(position).getId());
                            startActivity(intent);
                        }
                    });
                } else if (msg.arg1 == NetConfig.TaskId.recommendNewList) {
                    final InformationItem informationItem = gson.fromJson(msg.obj.toString(), InformationItem.class);
                    HomeFragmentHotInformationListViewAdapter homeFragmentHotInformationListViewAdapter =
                            new HomeFragmentHotInformationListViewAdapter(getContext(), informationItem);
                    svlist_fragment_home_information.setAdapter(homeFragmentHotInformationListViewAdapter);
                    svlist_fragment_home_information.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(getActivity(), InformationDetailActivity.class);
                            intent.putExtra("Id", informationItem.getList().get(position).getId());
                            startActivity(intent);
                        }
                    });
                } else if (msg.arg1 == 111 && isVisible()) {
                    hide(rl_fragment_home_message);
                } else if (msg.arg1 == NetConfig.TaskId.categoryIndex) {
                    WoodTypeImpl.analyWoodType(getContext(), msg.obj.toString());
                    initWoodType();
                }else if (msg.arg1 == 222){
                    if (runnableOrderIndex < shopOrders.size()) {
                        tv_fragment_home_message.setText(ShopOrder.initTitle(shopOrders.get(runnableOrderIndex)));
                        tv_fragment_home_message_date.setText(DateUtils.getTimeDifference(shopOrders.get(runnableOrderIndex).pay_time));
                        runnableOrderIndex++;
                    } else {
                        runnableOrderIndex = 0;
                        tv_fragment_home_message.setText(ShopOrder.initTitle(shopOrders.get(runnableOrderIndex)));
                        tv_fragment_home_message_date.setText(DateUtils.getTimeDifference(shopOrders.get(runnableOrderIndex).pay_time));
                        runnableOrderIndex++;
                    }
                    show(rl_fragment_home_message);
                }
            }

            return false;
        }
    });

    public void hide(RelativeLayout relativeLayout){
        Animation animation = new TranslateAnimation(0,0,
                relativeLayout.getRotationY(),relativeLayout.getRotationY() - relativeLayout.getHeight());
        animation.setDuration(300);
        animation.setFillAfter(true);
        relativeLayout.startAnimation(animation);
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.arg1 = 222;
                handler.sendMessage(message);
            }
        };
        timer.schedule(timerTask,200);
    }

    public void show(RelativeLayout relativeLayout){
        Animation animation = new TranslateAnimation(0,0,
                relativeLayout.getRotationY() + relativeLayout.getHeight(),relativeLayout.getRotationY());
        animation.setDuration(300);
        relativeLayout.startAnimation(animation);
    }


    Timer timer;

    private void runnableOrderInfo() {
        if (timer == null) {
            timer = new Timer();
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                    Message msg = new Message();
                    msg.arg1 = 111;
                    handler.sendMessage(msg);
                }
            };
            timer.schedule(task, 4000, 3000);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        edit_fragment_home_search.clearFocus();
        edit_fragment_home_search_top.clearFocus();
        if ((shopOrders == null || shopOrders.size() ==0) && !sv_fragment_home.isRefreshing()){
            getData();
        }
    }

    public void scrollViewTop() {
        sv_fragment_home.getRefreshableView().smoothScrollTo(0, lastScrollY);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_fragment_home_supplyanddemand:
                startActivity(new Intent(getActivity().getApplicationContext(), SupplyAndDemendActivity.class));
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (this.getView() != null)
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            startActivity(new Intent(getActivity(), SearchActivity.class));
        }
    }
}
